from openpyxl import Workbook 
from openpyxl import load_workbook
import os
import shutil
from shutil import copyfile
import json

final_path = "final"
video_path = "final/videos"
info_path = "final/info.xlsx"

block_path = "blocks"

def get_bili_cfg():
    json_file = "cfg.json"
    with open(json_file) as f:
        cfg = json.load(f)
    return cfg

def copy_file(path_read, path_write):
    names = os.listdir(path_read)
    for name in names:
        path_read_new = path_read + "/" + name
        path_write_new = path_write + "/" + name
        if os.path.isdir(path_read_new):
            if not os.path.exists(path_write_new):
                os.mkdir(path_write_new)
            copy_file(path_read_new, path_write_new)
        else:
            copyfile(path_read_new, path_write_new)

if not os.path.exists(final_path):
    os.mkdir(final_path)

# 删除已经存在的视频
if os.path.exists(video_path):
    shutil.rmtree(video_path)

if os.path.exists(info_path):
    os.remove(info_path)

# 创建视频目录
os.mkdir(video_path)

cfg = get_bili_cfg()

blocks = cfg["blocks"]

# 创建表格
final_wb = Workbook()
final_ws = final_wb.active

start_row = 2 # 第一行是标题

for i in range(0, blocks + 1): # one more block
    path = block_path + "/block" + str(i)
    video = path + "/videos"
    info = path + "/info.xlsx"
    
    if os.path.exists(path):
        # copy video
        if os.path.exists(video):
            copy_file(video, video_path) 

        # copy info
        if os.path.exists(info):
            # 打开文件
            wb = load_workbook(info)
            ws = wb.active

            if i == 0:
                # 复制标题
                for col in range(1, ws.max_column + 1):
                    final_ws.cell(1, col).value = ws.cell(1, col).value
            
            # 复制数据
            for item_idx in range(0, ws.max_row + 1 - 2): # skip title
                for col in range(1, ws.max_column + 1):
                    final_ws.cell(start_row, col).value = ws.cell(2 + item_idx, col).value
                start_row += 1

final_wb.save(info_path)
print("[INFO] 合并所有块成功！")
